layui.use(['layer', 'form','table'], function() {
    const layer = layui.layer;
    const $ = layui.$;
    const table = layui.table;
    const form = layui.form;


    let groupTab = table.render({
        elem: '#groupTab',
        url: '/activiti/group/list', //数据接口
        page: true, //开启分页
        request: {
            pageName: 'pageNum', // page
            limitName: 'pageSize' // limit
        },
        cols: [[ //表头
            {field: 'id', title: '用户组ID', width:150, sort: true, fixed: 'left'},
            {field: 'name', title: '用户组名称',fixed:'center',minWidth:400},
            {field: 'type',fixed:'center', title: '类型'},
            {field: 'zs',fixed:'center', title: '关联用户数'},
            {field: 'operate', title: '操作',fixed:'center',toolbar: '#operate'}
        ]],
        parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
            return {
                "code": res.code, //返回状态码
                "msg": res.msg, //解析提示信息
                "count": res.data.total, //后台返回的数据总条数，用于自定义分页使用
                "data": res.data.list //解析数据列表
            };
        }
    });


    form.on('submit(query)',function(data){
        groupTab.reload({
            where: data.field
            ,page: {
                curr: 1
            }
        });
        return false;
    });


    form.on('submit(add)',function(){
        let html = document.getElementById('addGroup').innerHTML;
        layer.open({
            title: '新增用户组',
            type: 1,
            content: html,
            area: ['650px', '400px'],
            btn: ['确定', '取消'],
            success:function(){
                form.render(null, 'addGroup');
            },
            yes: function(){
                $('#save').click();
            },
            btn2: function(){
                layer.closeAll();
            }
        });
        return false;
    });


    form.on('submit(save)',function(data){
        $.ajax({
            url:"/activiti/group/save",
            dataType:"json",
            data:data.field,
            type:"post",
            success:function(res){
                if (res.code==0){
                    groupTab.reload()
                    layer.closeAll()
                    layer.msg('保存成功!',{icon:6},3000)
                }else{
                    layer.msg(res.msg,{icon:5})
                }
            },
            error:function(){
                layer.msg("系统错误",{icon:5})
            }
        });
    });


    function addUserPage(groupId, groupUserTab){
        layer.open({
            title: '添加关联用户',
            type: 2,
            content: '/activiti/group/addUserPage?groupId='+groupId,
            area: ['800px', '480px'],
            btn: ['确定','取消'],
            yes:function(index, layero){
                let iframeWindow = window['layui-layer-iframe'+ index]
                let checkStatus = iframeWindow.layui.table.checkStatus('addUserTab');
                if (checkStatus.data.length==0){
                    layer.msg("请选择用户!",{icon:5});
                    return false;
                }
                let userIds = [];
                for (let i=0;i<checkStatus.data.length;i++){
                    userIds[i] = checkStatus.data[i].id;
                }
                let params = {
                    groupId: groupId,
                    userIds: userIds
                }
                $.ajax({
                    url:"/activiti/group/linkUser",
                    dataType:"json",
                    contentType:"application/json",
                    data: JSON.stringify(params),
                    type:"post",
                    success:function(res){
                        if (res.code==0){
                            layer.close(index)
                            layer.msg('关联成功',{icon:6})
                            groupUserTab.reload()
                        }else{
                            layer.msg(res.msg,{icon:5})
                        }
                    },
                    error:function(){
                        layer.msg('系统错误!',{icon:5})
                    }
                })
            },
            btn2:function(index, layero){
                layer.close(index)
            }
        })
    }

    table.on('tool(groupTab)', function (obj){
        if (obj.event == 'edit'){
            let html = document.getElementById('addGroup').innerHTML;
            layer.open({
                title: '修改用户组',
                type: 1,
                content: html,
                area: ['650px', '400px'],
                btn: ['确定', '取消'],
                success:function(){
                    form.val('addGroup',obj.data)
                    form.render(null, 'addGroup');
                },
                yes: function(){
                    $('#save').click();
                },
                btn2: function(){
                    layer.closeAll();
                }
            });
        }else if (obj.event == 'linkUser'){
            let groupId = obj.data.id;
            let html = document.getElementById('groupUser').innerHTML;
            layer.open({
                title: '关联用户',
                type: 1,
                content: html,
                area: ['900px', '500px'],
                btn: ['关闭'],
                success:function(index,layero){
                    let groupUserTab = table.render({
                        elem: '#groupUserTab',
                        url: '/activiti/group/userlist?groupId='+groupId, //数据接口
                        height:320,
                        cols: [[ //表头
                            {field: 'id', title: '用户ID', width:150, sort: true, fixed: 'left'},
                            {field: 'firstName', title: '用户名称'},
                            {field: 'lastName', title: '中文名'},
                            {field: 'operate', title: '操作',
                                templet:function (d) {
                                    return '<button class="layui-btn layui-btn-xs" lay-event="delLink">删除</button>';
                                }
                            }
                        ]],
                        parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
                            return {
                                "code": res.code, //返回状态码
                                "msg": res.msg, //解析提示信息
                                "data": res.data
                            };
                        }
                    });

                    table.on('tool(groupUserTab)', function (obbj){
                        if (obbj.event == 'delLink'){
                            $.ajax({
                                url:"/activiti/group/delLinkUser?groupId="+groupId+"&userId="+obbj.data.id,
                                type:"get",
                                success:function(res){
                                    if (res.code==0){
                                        groupUserTab.reload()
                                        layer.msg("删除成功",{icon:6})
                                    }else{
                                        layer.msg("删除失败",{icon:5})
                                    }
                                },
                                error:function(){
                                    layer.msg("系统错误",{icon:5})
                                }
                            })
                        }
                    })

                    $('#addUser').on('click',function(){
                        addUserPage(obj.data.id, groupUserTab)
                    })
                },
                yes: function(){
                    layer.closeAll();
                }
            });
        }
        else if (obj.event == 'del'){
            $.ajax({
                url:"/activiti/group/delete?id="+obj.data.id,
                type:"delete",
                success:function(res){
                    if (res.code==0){
                        groupTab.reload()
                        layer.msg(res.msg,{icon:6})
                    }else{
                        layer.msg(res.msg,{icon:5})
                    }
                },
                error:function(){
                    layer.msg("系统错误",{icon:5})
                }
            })
        }
    })

});